<?php
namespace app\know\controller;

use app\know\model\ChapterModel;
use app\know\controller\AdminKnowBaseController;
use app\know\validate\NewWordValidate;
use app\know\validate\ResourceValidate;
use app\know\validate\NewWordQuestionValidate;
use app\know\validate\NewWordExampleValidate;
use app\know\validate\NewWordExpandValidate;
use app\know\model\SysConfigModel;
use app\know\model\NewWordModel;
use app\know\model\NewWordExampleModel;
use app\know\model\NewWordExpandModel;
use app\know\model\NewWordQuestionModel;
use app\know\model\MaterialModel;
use app\know\model\TeachingMaterialNewWordModel;
use think\facade\Db;
use app\user\model\AssetModel;

/**
 * Class AdminNewWordController 生词管理控制器
 * @package app\know\controller
 */
class AdminNewWordController extends AdminKnowBaseController
{
    /**
     * 教材管理
     * @adminMenu(
     *     'name'   => '生词管理',
     *     'parent' => 'know/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> false,
     *     'order'  => 31000,
     *     'icon'   => '',
     *     'remark' => '教材管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('know_admin_new_word_index_view');

        if (!empty($content)) 
		{
            return $content;
        }

		$chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $nav = $this->request->param('nav', 'list');

        $where = ['is_delete' => 0];
        $materials = MaterialModel::where($where)
                                    ->order('order_number', 'desc')
                                    ->select();
        
		$this->assign('materials', $materials);
        $this->assign('material_uuid', $material_uuid);
        $this->assign('chapter_uuid', $chapter_uuid);
        $this->assign('nav', $nav);
        
        return $this->fetch();
    }
	
    public function list()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['is_delete' => 0];
        if ($chapter_uuid)
        {
            $where['chapter_uuid'] = $chapter_uuid;
        }

        $count = NewWordModel::where($where)->count();
        $rows = NewWordModel::where($where)
                                    ->page($pageNumber, $pageSize)
                                    ->select();

        $m = new ChapterModel();     
		foreach($rows as $k =>$v) 
		{
            $rows[$k]['chapter_name'] = $m->getChapterPath($v['chapter_uuid'], $v['material_uuid']);
            $material = MaterialModel::where(['uuid' => $v['material_uuid'], 'is_delete' => 0])->find();
            $rows[$k]['teaching_name'] = $material['name'];
        }

        // $ds = SysConfigModel::where([['type', 'in', ['SUBJECT', 'GRADE', 'TEXTBOOK_VERSION', 'TEXTBOOK_VOLUME']], ['is_delete', '=', 0]])->select();
		// foreach($rows as $k => $v) 
		// {
		// 	foreach($ds as $k1 => $v1) 
		// 	{
		// 		if ($v['grade_code'] == $v1['key'] && $v1['type'] == 'GRADE') 
		// 		{
		// 			$v['grade'] = $v1['value'];
		// 		} 
		// 		else if ($v['subject_code'] == $v1['key'] && $v1['type'] == 'SUBJECT') 
		// 		{
		// 			$v['subject'] = $v1['value'];
		// 		} 
		// 		else if ($v['textbook_version_code'] == $v1['key'] && $v1['type'] == 'TEXTBOOK_VERSION') 
		// 		{
		// 			$v['version'] = $v1['value'];
		// 		} 
		// 		else if ($v['textbook_volume_code'] == $v1['key'] && $v1['type'] == 'TEXTBOOK_VOLUME') 
		// 		{
		// 			$v['volume'] = $v1['value'];
		// 		}
		// 	}
		// }		
        $this->success('', null, ['rows' => $rows, 'total' => $count]);
    }
    
	public function add()
    {
        $param = $this->request->param();

        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];

        try 
		{
			$model = new NewWordModel();
			$param['uuid'] = $model->getUUID();
            $this->validateFailError($param, 'NewWord.add');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        Db::startTrans();
        try 
        {
            $row = NewWordModel::create($param);
            if ($param['material_uuid'] && $param['chapter_uuid'])
            {
                TeachingMaterialNewWordModel::create([
                    'material_uuid' => $param['material_uuid'], 
                    'chapter_uuid'=> $param['chapter_uuid'],
                    'new_word_uuid'=> $param['uuid'],
                    'create_user' => $user['user_login'],
                ]);

            }

            $example = $param['example'];
            $question = $param['question'];
            $expand = $param['expand'];

            // 示例
            $m = new NewWordExampleModel();
            foreach(json_decode(htmlspecialchars_decode($example), true) as $ex)
            {
                if (empty($ex['id']))
                {
                    $ex['uuid'] = $m->getUUID();
                    $ex['create_user'] = $user['user_login'];
                    $ex['new_word_uuid'] = $d['uuid'];
                    $this->validateFailError($ex, 'NewWordExample.add');
                    $row = NewWordExampleModel::create($ex);
                    if (empty($row)) 
                    {
                        throw new Exception('试题示例失败');
                    }
                }
            }

            // 拓展
            $m = new NewWordExpandModel();
            foreach(json_decode(htmlspecialchars_decode($expand), true) as $expl)
            {
                if (empty($expl['id']))
                {
                    $expl['uuid'] = $m->getUUID();
                    $expl['create_user'] = $user['user_login'];
                    $expl['new_word_uuid'] = $d['uuid'];
                    $this->validateFailError($expl, 'NewWordExpand.add');
                    $row = NewWordExpandModel::create($expl);
                    if (empty($row)) 
                    {
                        throw new Exception('试题扩展失败');
                    }
                }
            }
            
            // 试题
            foreach(json_decode(htmlspecialchars_decode($question), true) as $exp)
            {
                $exp['create_user'] = $user['user_login'];
                $exp['new_word_uuid'] = $d['uuid'];
                $this->validateFailError($exp, 'NewWordQuestion.add');
                $row = NewWordQuestionModel::create($exp);
                if (empty($row)) 
                {
                    throw new Exception('试题添加失败');
                }
            }
            if (empty($row)) 
            {
                throw new Exception('生词添加失败');
            }
            Db::commit();
        } 
        catch (\Exception $e) 
        {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->opLog([
            'table_name' => $model->getTableName(),
            'sql' => NewWordModel::getLastSql(),
            'create_user' => $user['user_login'],
        ]);
        $this->success('添加成功');
    }
	
	public function delete()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'NewWord.delete');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];

        try 
		{
            NewWordModel::where('id', 'in', preg_split("/[\s;,]/", $id))->save(['is_delete' => 1]);
            $this->opLog([
                'table_name' => (new NewWordModel())->getTableName(),
                'sql' => NewWordModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($id),
            ]);
        } 
		catch (\Throwable $th) 
		{
            $this->error($th->getMessage());
        }
        $this->success('已删除');
    }
	
	public function edit()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'NewWord.edit');
        } 
		catch (ValidateException $e) 
		{
            $this->log('ValidateException-' . __CLASS__ . __FUNCTION__ . $e->getError());
            $this->result('', 0, $e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];
        $param['modify_datetime'] = date("Y-m-d H:i:s");
        
        Db::startTrans();
        try 
		{
            
            $example = $param['example'];
            $question = $param['question'];
            $expand = $param['expand'];

            $d = NewWordModel::find($id);
            NewWordModel::update($param, ['id' => $id], NewWordModel::$UpdateField);

            // 示例
            $m = new NewWordExampleModel();
            foreach(json_decode(htmlspecialchars_decode($example), true) as $ex)
            {
                if (empty($ex['id']))
                {
                    $ex['uuid'] = $m->getUUID();
                    $ex['create_user'] = $user['user_login'];
                    $ex['new_word_uuid'] = $d['uuid'];
                    $this->validateFailError($ex, 'NewWordExample.add');
                    $row = NewWordExampleModel::create($ex);
                    if (empty($row)) 
                    {
                        throw new Exception('试题示例失败');
                    }
                }
            }

            // 拓展
            $m = new NewWordExpandModel();
            foreach(json_decode(htmlspecialchars_decode($expand), true) as $expl)
            {
                if (empty($expl['id']))
                {
                    $expl['uuid'] = $m->getUUID();
                    $expl['create_user'] = $user['user_login'];
                    $expl['new_word_uuid'] = $d['uuid'];
                    $this->validateFailError($expl, 'NewWordExpand.add');
                    $row = NewWordExpandModel::create($expl);
                    if (empty($row)) 
                    {
                        throw new Exception('试题扩展失败');
                    }
                }
            }

            // 试题
            foreach(json_decode(htmlspecialchars_decode($question), true) as $exp)
            {
                if (empty($exp['new_word_uuid']))
                {
                    $exp['create_user'] = $user['user_login'];
                    $exp['new_word_uuid'] = $d['uuid'];
                    $this->validateFailError($exp, 'NewWordQuestion.add');
                    $row = NewWordQuestionModel::create($exp);
                    if (empty($row)) 
                    {
                        throw new Exception('试题添加失败');
                    }
                }
            }
            $this->opLog([
                'table_name' => (new NewWordModel())->getTableName(),
                'sql' => NewWordModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($d),
            ]);
            Db::commit();
        } 
		catch (\Throwable $th) 
		{
            $this->log('Throwable-' . __CLASS__ . __FUNCTION__ . $th->getMessage() . NewWordModel::getLastSql());
            $this->error($th->getMessage());
        }
        $this->success('修改成功');
    }

    public function getItem()
    {
        $id = $this->request->param('id', '');

        $where = ['a.is_delete' => 0, 'a.id' => $id];
        $model = new NewWordModel();
        $row = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_material c', 'a.material_uuid = c.uuid')
                    ->leftJoin('cmf_know_chapter d', 'a.chapter_uuid = d.uuid and a.material_uuid = d.relate_uuid')
                    ->field('a.*, c.name as teaching_name, d.name as chapter_name')
                    ->find();
        if ($row['audio_asset_id'])
        {
            $audio_asset = AssetModel::find($row['audio_asset_id']);
            $row['audio_asset_url'] = $audio_asset ? cmf_get_file_download_url($audio_asset["file_path"]) : '';
        }
        else
        {
            $row['audio_asset_url'] = ''; 
        }

        $row['analysis'] = htmlspecialchars_decode(htmlspecialchars_decode($row['analysis']));

        $row['example'] = NewWordExampleModel::where(['is_delete' => 0, 'new_word_uuid' => $row['uuid']])->select();
        $row['expand'] = NewWordExpandModel::where(['is_delete' => 0, 'new_word_uuid' => $row['uuid']])->select();
        
        $qmodel = new NewWordQuestionModel();
        $row['question'] = $qmodel->where(['new_word_uuid' => $row['uuid']])
                                ->alias('a')
                                ->leftJoin('cmf_know_question b', 'a.question_uuid = b.uuid')
                                ->leftJoin('cmf_know_question_content c', 'b.uuid = c.question_uuid')
                                ->field('a.*, b.type_alias, c.content, c.answer')
                                ->select();
        foreach($row['question'] as $ques)
        {
            $ques['content'] = htmlspecialchars_decode(htmlspecialchars_decode($ques['content']));
        }

        $this->success('', null, $row);
    }

    public function maxOrder()
    {
        $order = NewWordModel::max('order_number');
        $this->success('', '', $order);
    }

    public function search()
    {
        $txt = $this->request->param('txt', '');

        $model = new NewWordModel();
        $rows = $model->where('a.content','like', $txt . '%')
                    ->alias('a')
                    ->page(1, 10)
                    ->select()
                    ->toArray();

        foreach ($rows as $k => $v)
        {
            if ($v['audio_asset_id'])
            {
                $audio_asset = AssetModel::find($v['audio_asset_id']);
                $rows[$k]['audio_asset_url'] = $audio_asset ? cmf_get_file_download_url($audio_asset["file_path"]) : '';
            }
            else
            {
                $rows[$k]['audio_asset_url'] = ''; 
            }
        }

        $this->success('', null, $rows);
    }
}
